from flask import Blueprint, render_template, request
from flask_login import login_required, login_user

from com.auth import admin_required
from qingdeng.orms import ArticleORM, CategoryORM, UserORM

admin_bp = Blueprint("admin_bp", __name__, url_prefix="/admin")


@admin_bp.route("/")
@admin_required
def admin_index():
    return render_template("admin/index.html")


@admin_bp.route("/admin")
@admin_required
def admin_view():
    return render_template("admin/admin.html")


@admin_bp.route("/login", methods=["POST", "GET"])
def login_view():
    if request.method == "GET":
        return render_template("admin/login.html")
    else:
        username = request.json.get("username")
        password = request.json.get("password")
        # 用户登录逻辑
        user: UserORM = UserORM.query.filter_by(mobile=username).first()
        if not user:
            return {"status": "fail", "message": "用户名不存在"}
        if not user.check_password(password):
            return {"status": "fail", "message": "密码错误"}
        # 必须是管理员才能进行登录
        if not user.is_admin:
            return {"status": "fail", "message": "不是管理员"}

        # 记录用户的信息
        login_user(user, remember=True)
        # 要不记录管理员的信息 user.is_admin
        # session['is_admin'] = True  # 管理员可以记录到session, 也可以不记录到session
        return {
            "status": "success",
            "message": "登录成功",
            "next": request.json.get("next", None),
        }


@admin_bp.route("/user")
def admin_user_view():
    return render_template("admin/user/index.html")


@admin_bp.route("/user/add")
def admin_user_add_view():
    return render_template("admin/user/user_add.html")


@admin_bp.route("/user/edit")
def admin_user_edit_view():
    return render_template("admin/user/user_edit.html")


@admin_bp.route("/articles")
def admin_article_view():
    return render_template("admin/articles/articles.html")


@admin_bp.route("/articles_verify", methods=["GET", "PUT"])
def articles_verify_view():
    if request.method == "GET":
        # 审核文章的时候需要加载文章数据
        article_id = request.args.get("article_id")
        article = ArticleORM.query.get(int(article_id))
        cate_list = CategoryORM.query.all()
        return render_template(
            "admin/articles/article_review.html", article=article, cate_list=cate_list
        )
    article_id = request.json.get("id")
    status = request.json.get("status")
    article: ArticleORM = ArticleORM.query.get(int(article_id))
    article.status = int(status)
    article.save_to_db()
    return {"status": "success", "message": "审核成功"}


@admin_bp.route("/category")
def admin_category_view():
    return render_template("admin/articles/category.html")
